package cn.taoticket.service.impl;

import cn.taoticket.client.*;
import cn.taoticket.common.*;
import cn.taoticket.exception.OrderErrorCode;
import cn.taoticket.pojo.*;
import cn.taoticket.service.OrderService;
import cn.taoticket.vo.CreateOrderVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
public class OrderServiceImpl implements OrderService {
    @Resource
    private RestTaoticketItemClient restTaoticketItemClient;
    @Resource
    private RestTaoticketSchedulerSeatClient restTaoticketSchedulerSeatClient;
    @Resource
    private RestTaoticketSchedulerSeatPriceClient restTaoticketSchedulerSeatPriceClient;
    @Resource
    private RestTaoticketOrderClient restTaoticketOrderClient;
    @Resource
    private RestTaoticketLinkUserClient restTaoticketLinkUserClient;
    @Resource
    private RestTaoticketOrderLinkUserClient restTaoticketOrderLinkUserClient;
    @Override
    public Dto createOrder(CreateOrderVo orderVo) throws Exception {
        //先查询数据库有没有对应的商品信息可以下单，如果没有，直接返回错误
        TaoticketItem taoticketItem = restTaoticketItemClient.getTaoticketItemById(orderVo.getItemId());
        if (EmptyUtils.isEmpty(taoticketItem)) {
            throw new BaseException(OrderErrorCode.ORDER_NO_DATA);
        }
        //拆分座位集合信息，以坐标x_y的形式定位座位，多个座位用' ，'分割,座位有4种状态(status)（0没座位，1有座位，2被锁定待付款，3已售出）
        String[] seatArr = orderVo.getSeatPositions().split(",");
        String[] seats;
        double totalPrice = 0.0;
        Double[] priceDoubles = new Double[seatArr.length];
        //生成订单编号
        String orderNo = IdWorker.getId();
        for (int i = 0; i < seatArr.length; i++) {
            //获取座位的横纵坐标x_y
            seats = seatArr[i].split("_");
            //查询每个座位的信息
            TaoticketSchedulerSeat schedulerSeat = restTaoticketSchedulerSeatClient.getTaoticketSchedulerSeatByOrder(
                    orderVo.getSchedulerId(),
                    Integer.parseInt(seats[0]),
                    Integer.parseInt(seats[1])
            );
            //更新座位状态为锁定待付款状态
            schedulerSeat.setStatus(Constants.SchedulerSeatStatus.SchedulerSeat_TOPAY);
            //更新下单用户
            schedulerSeat.setUserId(orderVo.getUserId());
            //更新下单时间
            schedulerSeat.setUpdatedTime(new Date());
            //更新订单编号(注：编号需要生成，下面OrderUtils.createOrderNo()生成方法不够复杂高并发环境下有重复的风险，所以不用了)
//            schedulerSeat.setOrderNo(OrderUtils.createOrderNo());
            //用这个工具类取代上面的
            schedulerSeat.setOrderNo(orderNo);
            //更新数据库
            restTaoticketSchedulerSeatClient.qdtxModifyTaoticketSchedulerSeat(schedulerSeat);
            //计算总票价(通过排期id和座位的级别(级别不同价格不同)查询)
            TaoticketSchedulerSeatPrice schedulerSeatPrice = restTaoticketSchedulerSeatPriceClient.getTaoticketSchedulerSeatPriceByScheduleIdAndArea(
                    schedulerSeat.getScheduleId(),
                    schedulerSeat.getAreaLevel());
            totalPrice += schedulerSeatPrice.getPrice();
            //保存座位价格信息
            priceDoubles[i] = schedulerSeatPrice.getPrice();
        }
        //以下操作生成订单信息并保存到数据库
        TaoticketOrder taoticketOrder = new TaoticketOrder();
        taoticketOrder.setOrderNo(orderNo);
        BeanUtils.copyProperties(orderVo, taoticketOrder);
        taoticketOrder.setItemName(taoticketItem.getItemName());
        //设置状态为待支付
        taoticketOrder.setOrderType(Constants.SchedulerSeatStatus.SchedulerSeat_TOPAY);
        taoticketOrder.setTotalCount(seatArr.length);
        //如果勾选（购买）了保险，需要将保险费用增加到总金额里
        Integer isNeedInsurance = orderVo.getIsNeedInsurance();
        if (isNeedInsurance == Constants.OrderStatus.ISNEEDINSURANCE_YES) {
            //添加保险金额到总价格
            totalPrice += Constants.OrderStatus.NEEDINSURANCE_MONEY;
        }
        //设置保险的金额
        taoticketOrder.setInsuranceAmount(Constants.OrderStatus.NEEDINSURANCE_MONEY);
        //订单创建时间
        taoticketOrder.setCreatedTime(new Date());
        //更新到数据库,并且返回当前订单数据的主键id
        Long aLong = restTaoticketOrderClient.qdtxAddTaoticketOrder(taoticketOrder);
        //更新相关关联用户
        String[] linkIds = orderVo.getLinkIds().split(",");
        TaoticketLinkUser taoticketLinkUser;
        for (int i = 0; i < linkIds.length; i++) {
            //查询关联用户信息
            taoticketLinkUser = restTaoticketLinkUserClient.getTaoticketLinkUserById(Long.parseLong(linkIds[i]));
            if (EmptyUtils.isEmpty(taoticketLinkUser)) {
                throw new BaseException(OrderErrorCode.ORDER_NO_DATA);
            }
            TaoticketOrderLinkUser taoticketOrderLinkUser = new TaoticketOrderLinkUser();
            taoticketOrderLinkUser.setOrderId(aLong);
            taoticketOrderLinkUser.setLinkUserId(taoticketLinkUser.getId());
            taoticketOrderLinkUser.setLinkUserName(taoticketLinkUser.getName());
            taoticketOrderLinkUser.setX(Integer.parseInt(seatArr[i].split("_")[0]));
            taoticketOrderLinkUser.setY(Integer.parseInt(seatArr[i].split("_")[1]));
            taoticketOrderLinkUser.setPrice(priceDoubles[i]);
            taoticketOrderLinkUser.setCreatedTime(new Date());
            restTaoticketOrderLinkUserClient.qdtxAddTaoticketOrderLinkUser(taoticketOrderLinkUser);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderNo", orderNo);
        return DtoUtil.returnDataSuccess(jsonObject);
    }
}
